package cn.afactory.tygz.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import cn.afactory.tygz.R;
import cn.afactory.tygz.TianYaGongZaiApplication;
import cn.afactory.tygz.controller.MessageController;
import cn.afactory.tygz.db.DBManager;
import cn.afactory.tygz.model.MessageDetail;
import cn.afactory.tygz.model.MessageDetailList;
import cn.afactory.tygz.net.NetManager;
import cn.afactory.tygz.net.lsn.OnResponseListener;
import cn.afactory.tygz.ui.adapter.FaceAdapter;
import cn.afactory.tygz.ui.adapter.FacePageAdeapter;
import cn.afactory.tygz.ui.adapter.PrivateMessageAdapter;
import cn.afactory.tygz.ui.base.BaseActivity;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshBase;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshListView;
import cn.afactory.tygz.ui.base.utils.InputMethodUtils;
import cn.afactory.tygz.ui.base.utils.LocalUtils;
import cn.afactory.tygz.ui.base.utils.SPUtils;
import cn.afactory.tygz.ui.base.utils.sns.Tools;
import cn.afactory.tygz.ui.view.CirclePageIndicator;
import cn.afactory.tygz.ui.view.JazzyViewPager;

/**
 * Created with Android Studio.
 * Title:PrivateMsgActivity
 * Description:
 * Copyright:Copyright (c) 2015
 * Company:和平必胜、正义必胜、人民必胜
 * Author:炎黄子孙
 * Date:15/9/22
 * Time:下午4:38
 * Version 1.0
 */
public class PrivateMsgActivity extends BaseActivity implements View.OnClickListener{
    public static int MSGPAGERNUM;

    public static int defaultCount = 0;

    private ImageButton mFaceBtn;
    private boolean isFaceShow = false;
    private InputMethodManager mInputMethodManager;
    private EditText mEtMsg;

    private LinearLayout mllFace;// 表情显示的布局
    private JazzyViewPager mFaceViewPager;// 表情viewpager
    private int mCurrentPage = 0;// 表情页数
    private List<String> mKeyList;// 表情list

    private TextView mBtnSend;// 发送消息按钮
    private WindowManager.LayoutParams mParams;

    // 接受数据
    private MessageController mController;
    private long mUserId;
    private String mNickName;
    private String mUserIcon;
    private int mPageIndex;
    private int mPageSize = 10;

    private List<MessageDetail> mList = new ArrayList<>();
    private PrivateMessageAdapter mAdapter;
    /**
     * 跳转到私信详情页面
     * @param context
     * @param userId
     */
    public static void gotoMessageDetail(Context context,long userId,String nickName,String userIcon){
        Intent intent = new Intent(context,PrivateMsgActivity.class);
        intent.putExtra(SPUtils.EXTRA_USER_ID,userId);
        intent.putExtra(SPUtils.EXTRA_NICK_NAME,nickName);
        intent.putExtra(SPUtils.EXTRA_USER_ICON,userIcon);
        context.startActivity(intent);
    }

    /**
     * 表情viewPager切换效果
     */
    private JazzyViewPager.TransitionEffect mEffects[] = { JazzyViewPager.TransitionEffect.Standard,
            JazzyViewPager.TransitionEffect.Tablet, JazzyViewPager.TransitionEffect.CubeIn,
            JazzyViewPager.TransitionEffect.CubeOut, JazzyViewPager.TransitionEffect.FlipVertical,
            JazzyViewPager.TransitionEffect.FlipHorizontal, JazzyViewPager.TransitionEffect.Stack,
            JazzyViewPager.TransitionEffect.ZoomIn, JazzyViewPager.TransitionEffect.ZoomOut,
            JazzyViewPager.TransitionEffect.RotateUp, JazzyViewPager.TransitionEffect.RotateDown,
            JazzyViewPager.TransitionEffect.Accordion, };// 表情翻页效果

    /**
     * @Description 滑动到列表底部
     */
    private void scrollToBottomListItem() {

        // todo eric, why use the last one index + 2 can real scroll to the
        // bottom?
        if (plistview != null) {
            ListView lv = plistview.getRefreshableView();
            lv.setSelection(mAdapter.getCount() + 1);
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_private_message_detail);

        mController = new MessageController(this,mUIHandler);
        mParams = getWindow().getAttributes();
        mUserId = getIntent().getLongExtra(SPUtils.EXTRA_USER_ID, -1);
        mNickName = getIntent().getStringExtra(SPUtils.EXTRA_NICK_NAME);
        mUserIcon = getIntent().getStringExtra(SPUtils.EXTRA_USER_ICON);

        DBManager.getInstance(getApplicationContext()).resetMsgUnRead(mUserId);

        if(mNickName != null){
            setTitleText(mNickName);
        }

        mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        Set<String> keySet = TianYaGongZaiApplication.getInstance().getFaceMap()
                .keySet();
        mKeyList = new ArrayList<String>();
        mKeyList.addAll(keySet);

        MSGPAGERNUM = 0;
        initView();

        initFacePage();

        initDatas();
//        mUserDB = mApplication.getUserDB();
    }

    @Override
    public void handleMessage(Message msg) {
       switch (msg.what){
           case MessageController.MSG_LOAD_PRIVATE_MESSAGE_DETAIL_OK:
               handleMsgList((MessageDetailList)msg.obj);
               break;
           case MessageController.MSG_LOAD_PRIVATE_MESSAGE_DETAIL_KO:
               break;
       }
        // 结束下拉刷新
        if (plistview.isRefreshing()) {
            plistview.onRefreshComplete();
        }
    }

    private void handleMsgList(MessageDetailList t){
        if(t != null && t.value.size() >= 0){
            mList.addAll(t.value);
            mAdapter.setDatas(mList);
            mPageIndex = (mList.size()/mPageSize) + 1;
            setListListener();

            if (plistview.isRefreshing()) {
                plistview.onRefreshComplete();
            }
            if (t.value.size() < mPageSize) {
                plistview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
            } else {
                plistview.setMode(PullToRefreshBase.Mode.BOTH);
            }
        }
    }

    private void setListListener(){
        plistview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                startLoadMsgList(true);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                startLoadMsgList(false);
            }
        });
    }

    private void initDatas(){
        mAdapter = new PrivateMessageAdapter(this,mList,mUserIcon);
        plistview.setAdapter(mAdapter);

        plistview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                InputMethodUtils.autoDismiss(mEtMsg);
                return false;
            }
        });

        mController.doGetPrivateMsgList(mUserId, mPageIndex, mPageSize, System.currentTimeMillis());

    }

    private void startLoadMsgList(boolean cleanData){
        if(cleanData){
            mList.clear();
            mPageIndex = 1;
        }

        mController.doGetPrivateMsgList(mUserId,mPageIndex,mPageSize,System.currentTimeMillis());
    }
    
    private void initView() {
        mFaceBtn = (ImageButton) findViewById(R.id.ib_face);
        mEtMsg = (EditText) findViewById(R.id.et_msg_content);
        mFaceBtn.setOnClickListener(this);
        mllFace = (LinearLayout) findViewById(R.id.ll_face_pictures);
        mFaceViewPager = (JazzyViewPager) findViewById(R.id.jvp_face);
        mBtnSend = (TextView) findViewById(R.id.btn_msg_send);
        mBtnSend.setClickable(true);
        mBtnSend.setEnabled(true);
        mBtnSend.setOnClickListener(this);

        mAdapter = new PrivateMessageAdapter(this, initMsgData(),mUserIcon);
        plistview = (PullToRefreshListView) findViewById(R.id.lv_msg_list);
        // 触摸ListView隐藏表情和输入法
        plistview.setAdapter(mAdapter);
        mEtMsgOnKeyListener();
    }
    //重新加载数据库的数据
    private void reloadMsgList(MessageDetail messageDetail){
        mList.add(messageDetail);
        mAdapter.setDatas(mList);
    }
   
    /**
     * 输入框key监听事件
     */
    private void mEtMsgOnKeyListener() {
        mEtMsg.setOnKeyListener(new View.OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // TODO Auto-generated method stub
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    if (mParams.softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE
                            || isFaceShow) {
                        mllFace.setVisibility(View.GONE);
                        isFaceShow = false;
                        // imm.showSoftInput(msgEt, 0);
                        return true;
                    }
                }
                return false;
            }
        });
        mEtMsg.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
//                if (s.length() > 0) {
//                    mBtnSend.setEnabled(true);
//                    mBtnSend.setVisibility(View.VISIBLE);
//                } else {
//                    mBtnSend.setEnabled(false);
//                    mBtnSend.setVisibility(View.GONE);
//                }
            }
        });
    }
    
    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {
        mInputMethodManager.hideSoftInputFromWindow(mEtMsg.getWindowToken(), 0);
        mllFace.setVisibility(View.GONE);
        isFaceShow = false;
        super.onPause();
    }

    /**
     * 加载消息历史，从数据库中读出
     */
    private List<MessageDetail> initMsgData() {
        List<MessageDetail> list = DBManager.getInstance(getApplicationContext()).getMessageListByUserId(mUserId,
                mPageIndex,
                mPageSize,
                System.currentTimeMillis());
        return list;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ib_face: {
                if (!isFaceShow) {
                    mFaceBtn.setImageResource(R.drawable.message_keyboard_background);
                    mInputMethodManager.hideSoftInputFromWindow(
                            mEtMsg.getWindowToken(), 0);
                    try {
                        Thread.sleep(80);// 解决此时会黑一下屏幕的问题
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    mllFace.setVisibility(View.VISIBLE);
                    isFaceShow = true;
                } else {
                    mFaceBtn.setImageResource(R.drawable.message_emotion_background);
                    mllFace.setVisibility(View.GONE);
                    isFaceShow = false;
                }
                break;
            }

            case R.id.btn_msg_send: {
                // 发送消息
                doSendMsg();
                break;
            }
        }
    }

    /**
     * 发送私信
     */
    private void doSendMsg(){
        final String msg = mEtMsg.getText().toString();
        if(msg.length() == 0){
            return ;
        }
        showLoadingView("发送中...");
        NetManager.getInstance(this).doSendMsg(mUserId,msg, new OnResponseListener<Boolean>() {
            @Override
            public void onInternError(int errorCode, String errorMessage) {
                hideLoadingView();
                LocalUtils.showToast(PrivateMsgActivity.this,errorMessage);
        }

            @Override
            public void onComplete(boolean isOK, Boolean result, int errorCode, String errorMsg) {
                hideLoadingView();
                if(isOK){
                    MessageDetail messageDetail = DBManager.getInstance(getApplicationContext()).
                            insertNewMessage(msg, mUserId, mNickName, mUserIcon);
                    if(messageDetail != null) {
                        reloadMsgList(messageDetail);
                    }
                    scrollToBottomListItem();
                    mEtMsg.setText("");
                    LocalUtils.sendBroadcast(mContext, SPUtils.BR_ACTION_SYNC_MESSAGE_OK);
                }else{
                    LocalUtils.showToast(PrivateMsgActivity.this,errorMsg);
                }
            }
        });
    }

    /**
     * 表情viwepager
     */
    private void initFacePage() {
        List<View> lv = new ArrayList<View>();
        for (int i = 0; i < TianYaGongZaiApplication.NUM_PAGE; ++i) {
            lv.add(getGridView(i));
        }
        FacePageAdeapter adapter = new FacePageAdeapter(lv, mFaceViewPager);
        mFaceViewPager.setAdapter(adapter);
        mFaceViewPager.setCurrentItem(mCurrentPage);
//        mFaceViewPager.setTransitionEffect(mEffects[mSpUtil.getFaceEffect()]);// 效果
        CirclePageIndicator indicator = (CirclePageIndicator) findViewById(R.id.cpi_indicator);// 圆点
        indicator.setViewPager(mFaceViewPager);
        adapter.notifyDataSetChanged();
        mllFace.setVisibility(View.GONE);
        indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                mCurrentPage = arg0;
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // do nothing
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // do nothing
            }
        });

    }

    /**
     * 获取表情GridView
     *
     * @param i
     * @return
     */
    private GridView getGridView(int i) {
        GridView gv = new GridView(this);
        gv.setNumColumns(7);
        gv.setSelector(new ColorDrawable(Color.TRANSPARENT));// 屏蔽GridView默认点击效果
        gv.setBackgroundColor(Color.TRANSPARENT);
        gv.setCacheColorHint(Color.TRANSPARENT);
        gv.setHorizontalSpacing(1);
        gv.setVerticalSpacing(1);
        gv.setLayoutParams(new GridView.LayoutParams(GridView.LayoutParams.MATCH_PARENT,
                GridView.LayoutParams.MATCH_PARENT));
        gv.setGravity(Gravity.CENTER);
        gv.setAdapter(new FaceAdapter(this, i));
        gv.setOnTouchListener(forbidenScroll());
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View view,
                                    int position, long arg3) {
                if (position == TianYaGongZaiApplication.NUM) {// 删除键的位置
                    int selection = mEtMsg.getSelectionStart();
                    String text = mEtMsg.getText().toString();
                    if (selection > 0) {
                        String text2 = text.substring(selection - 1);
                        if ("]".equals(text2)) {
                            int start = text.lastIndexOf("[");
                            int end = selection;
                            mEtMsg.getText().delete(start, end);
                            return;
                        }
                        mEtMsg.getText().delete(selection - 1, selection);
                    }
                } else {// 选择表情==
                    int count = mCurrentPage * TianYaGongZaiApplication.NUM + position;
                    defaultCount = count;
                    // 注释的部分，在EditText中显示字符串
                    // String ori = msgEt.getText().toString();
                    // int index = msgEt.getSelectionStart();
                    // StringBuilder stringBuilder = new StringBuilder(ori);
                    // stringBuilder.insert(index, keys.get(count));
                    // msgEt.setText(stringBuilder.toString());
                    // msgEt.setSelection(index + keys.get(count).length());

                    // 下面这部分，在EditText中显示表情
                    Bitmap bitmap = BitmapFactory.decodeResource(
                            getResources(), (Integer) TianYaGongZaiApplication
                                    .getInstance().getFaceMap().values()
                                    .toArray()[count]);
                    if (bitmap != null) {
                        int rawHeigh = bitmap.getHeight();
                        int rawWidth = bitmap.getHeight();
                        // 设置表情的大小===
                        int newHeight = Tools.dip2px(PrivateMsgActivity.this, 30);
                        int newWidth = Tools.dip2px(PrivateMsgActivity.this, 30);
                        // 计算缩放因子
                        float heightScale = ((float) newHeight) / rawHeigh;
                        float widthScale = ((float) newWidth) / rawWidth;
                        // 新建立矩阵
                        Matrix matrix = new Matrix();
                        matrix.postScale(heightScale, widthScale);
                        // 设置图片的旋转角度
                        // matrix.postRotate(-30);
                        // 设置图片的倾斜
                        // matrix.postSkew(0.1f, 0.1f);
                        // 将图片大小压缩
                        // 压缩后图片的宽和高以及kB大小均会变化
                        Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                                rawWidth, rawHeigh, matrix, true);
                        ImageSpan imageSpan = new ImageSpan(PrivateMsgActivity.this,
                                newBitmap);
                        String emojiStr = mKeyList.get(count);
                        SpannableString spannableString = new SpannableString(
                                emojiStr);
                        spannableString.setSpan(imageSpan,
                                emojiStr.indexOf('['),
                                emojiStr.indexOf(']') + 1,
                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        mEtMsg.append(spannableString);
                    } else {
                        String ori = mEtMsg.getText().toString();
                        int index = mEtMsg.getSelectionStart();
                        StringBuilder stringBuilder = new StringBuilder(ori);
                        stringBuilder.insert(index, mKeyList.get(count));
                        mEtMsg.setText(stringBuilder.toString());
                        mEtMsg.setSelection(index
                                + mKeyList.get(count).length());
                    }
                }
            }
        });
        return gv;
    }


    // 防止乱pageview乱滚动
    private View.OnTouchListener forbidenScroll() {
        return new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    return true;
                }
                return false;
            }
        };
    }

}